package com.xdap.keymen.service.punch;

import com.definesys.mpaas.query.MpaasQuery;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.xdap.keymen.config.PunchConfig;
import com.xdap.keymen.entity.*;
import com.xdap.keymen.utils.OKHttpUtils;
import com.xdap.motor.entity.SnowflakeIdWorker;
import com.xdap.motor.vo.ResponseVo;
import com.xdap.runtime.service.RuntimeAppContextService;
import com.xdap.runtime.service.RuntimeDatasourceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class PunchOrderService extends PunchBaseService{
    private final RuntimeDatasourceService runtimeDatasourceService;
    private final RuntimeAppContextService runtimeAppContextService;
    private final SnowflakeIdWorker snowflakeIdWorker;

    private final PunchConfig punchConfig;

    private final PunchCustomerService punchCustomerService;

    private final PunchEmployeeService punchEmployeeService;



    @Autowired
    OKHttpUtils okHttpUtils;

    public ResponseVo getOrderList(Long rv) {
        //为空则到表中取
        if (rv==null) {
            rv=getMaxRvid("punch_sales_order");
        }

        Gson gson = new GsonBuilder().create();
        Map<String, String> params=new HashMap<>();
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        params.put("startDate", startDate);
//        params.put("endDate",endDate);
        Map<String, String> headers=new HashMap<>();
        //每页条数
        int sz=100;
        //页面

        //记录总数
        //int maxCount=this.countOrders(rv);
        int maxCount=100;
        log.info("最大记录数maxCount:{}",maxCount);
        //测试，先默认
        //maxCount=100;
        // 计算总页数 (向上取整)
        int totalPages = (int) Math.ceil((double) maxCount / sz);
        for (int currentPage = pg; currentPage <= totalPages; currentPage++) {
            headers=new HashMap<>();
            headers.put("Authorization", "Bearer "+getPunchToken());
            String response = okHttpUtils.doGet(punchConfig.getUrl().concat("/CRM/api/CO/"+rv.toString()+"/"+sz+"/"+currentPage), params,headers);
            PunchResponse punchResponse = gson.fromJson(response, new TypeToken<PunchResponse>(){}.getType());
            List<PunchOrderResponseEntity> list = gson.fromJson(punchResponse.getResult(), new TypeToken<List<PunchOrderResponseEntity>>(){}.getType());
            for(PunchOrderResponseEntity punchOrderResponseEntity:list){
                saveOrUpdateOrder(punchOrderResponseEntity);
                //保存明细
                //saveOrderProductByNo(removeSpaces(punchOrderResponseEntity.getCo_num()));
            }

            // 如果已经是最后一页，退出循环
            if (currentPage == totalPages) {
                break;
            }
        }

        return ResponseVo.ok().setData(maxCount);
    }


    private void saveOrUpdateOrder(PunchOrderResponseEntity entity) {
        String strInSales=removeSpaces(entity.getIn_saler());
        String strInSalesName="";
        PunchEmployeeEntity inSales = punchEmployeeService.getUserByGonghao(strInSales);
        if(inSales!=null){
            strInSalesName=inSales.getUsername();
        }

        String strSlsman=removeSpaces(entity.getSlsman());
        String strSlsmanName="";
        PunchEmployeeEntity slsman = punchEmployeeService.getUserByGonghao(strSlsman);
        if(slsman!=null){
            strSlsmanName=slsman.getUsername();
        }

        PunchSalesClientEntity punchSalesClientEntity=punchCustomerService.getCustomerByNumber(removeSpaces(entity.getCust_num()));
        String clientId="";
        String deptId="";
        if(punchSalesClientEntity!=null){
            clientId=punchSalesClientEntity.getId();
            deptId=punchSalesClientEntity.getAffiliatedBusinessOffice();
        }
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.sql("select id from punch_sales_order where sales_order_number='"+entity.getCo_num()+"'");
        String id= query.doQueryFirst(String.class);
        if (id!=null) {
            //更新
            query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
            query.update("client_name", removeSpaces(entity.getName()));
            query.update("client_number","[\"".concat(clientId).concat("\"]"));
            query.update("order_date",removeSpaces(entity.getOrder_date()));
            query.update("salesperson",strSlsman);
            query.update("salesperson_name",strSlsmanName);
            query.update("sales_back_office",strInSales);
            query.update("in_sales_name",strInSalesName);
            query.update("area",removeSpaces(entity.getArea()));
            //TODU 待完成
            query.update("business_office",deptId);
            query.update("remark",removeSpaces(entity.getMemo()));
            query.update("tax_code",removeSpaces(entity.getTax_code()));
            query.update("curr_code",removeSpaces(entity.getCurr_code()));
            query.update("rvid",entity.getRvid());
            query.update("last_update_date",new Date());
            query.eq("sales_order_number", entity.getCo_num());
            query.doUpdate(PunchOrderEntity.class);
        }else{

            //新增
            PunchOrderEntity punchOrderEntity = new PunchOrderEntity();
            punchOrderEntity.setId(snowflakeIdWorker.nextId());
            punchOrderEntity.setDocumentId(snowflakeIdWorker.nextId());
            punchOrderEntity.setClientName(removeSpaces(entity.getName()));
            punchOrderEntity.setClientNumber("[\"".concat(clientId).concat("\"]"));
            punchOrderEntity.setOrderDate(removeSpaces(entity.getOrder_date()));
            punchOrderEntity.setSalesPerson(strSlsman);
            punchOrderEntity.setSalesPersonName(strSlsmanName);
            punchOrderEntity.setSalesBackOffice(strInSales);
            punchOrderEntity.setInSalesName(strInSalesName);
            punchOrderEntity.setSalesOrderNumber(removeSpaces(entity.getCo_num()));

            punchOrderEntity.setArea(removeSpaces(entity.getArea()));
            punchOrderEntity.setBusinessOffice(deptId);
            punchOrderEntity.setRvid(entity.getRvid());
            punchOrderEntity.setRemark(removeSpaces(entity.getMemo()));
            punchOrderEntity.setTaxCode(removeSpaces(entity.getTax_code()));
            punchOrderEntity.setCurrCode(removeSpaces(entity.getCurr_code()));

            query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
            query.doInsert(punchOrderEntity);
        }

    }

    public int countOrders(Long rv) {
        int count=0;
        Gson gson = new GsonBuilder().create();
        Map<String, String> params=new HashMap<>();
        Map<String, String> headers=new HashMap<>();
        //https://pisi.punch.com.cn:8498/CRM/api/CO/Count/{rv}
        String response = okHttpUtils.doGet(punchConfig.getUrl().concat("/CRM/api/CO/Count/"+rv.toString()), params,headers);
        PunchResponse punchResponse = gson.fromJson(response, new TypeToken<PunchResponse>(){}.getType());
        count=Integer.parseInt(punchResponse.getResult());
        return count;
    }

    public ResponseVo getOrderItemList(Long rv) {
        //为空则到表中取
        if (rv==null) {
            //1=punch_sales_client
            rv=getMaxRvid("3");
        }
        Gson gson = new GsonBuilder().create();
        Map<String, String> params=new HashMap<>();
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        params.put("startDate", startDate);
//        params.put("endDate",endDate);
        Map<String, String> headers=new HashMap<>();
        //每页条数
        int sz=10;
        //页面
        int pg=1;
        //记录总数
        //int maxCount=this.countOrderItems(rv);
        //log.info("最大记录数maxCount:{}",maxCount);
        //测试，先默认
        int maxCount=130;
        // 计算总页数 (向上取整)
        int totalPages = (int) Math.ceil((double) maxCount / sz);
        for (int currentPage = pg; currentPage <= totalPages; currentPage++) {
            headers=new HashMap<>();
            headers.put("Authorization", "Bearer "+getPunchToken());
            //https://pisi.punch.com.cn:8498/CRM/api/CO/{rv}/{sz}/{pg}
            String response = okHttpUtils.doGet(punchConfig.getUrl().concat("/CRM/api/COItem/"+rv.toString()+"/"+sz+"/"+currentPage), params,headers);
            PunchResponse punchResponse = gson.fromJson(response, new TypeToken<PunchResponse>(){}.getType());
            //String result =punchResponse.getResult();
            List<PunchOrderItemResponseEntity> list = gson.fromJson(punchResponse.getResult(), new TypeToken<List<PunchOrderItemResponseEntity>>(){}.getType());
            for(PunchOrderItemResponseEntity punchOrderItemResponseEntity:list){
                saveOrUpdateOrderItem(punchOrderItemResponseEntity);
            }

            // 如果已经是最后一页，退出循环
            if (currentPage == totalPages) {
                break;
            }
        }

        return ResponseVo.ok().setData(maxCount);
    }

    private void saveOrUpdateOrderItem(PunchOrderItemResponseEntity entity) {
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.sql("select id from punch_sales_order_product where co_num='"+removeSpaces(entity.getCo_num())+"' and sales_order_line_number="+entity.getCo_line());
        String id= query.doQueryFirst(String.class);
        //订单主表
        query.sql("select * from punch_sales_order where sales_order_number='"+removeSpaces(entity.getCo_num())+"'");
        PunchOrderEntity punchOrderEntity= query.doQueryFirst(PunchOrderEntity.class);
        String tabId="";
        if (punchOrderEntity!=null) {
            tabId=punchOrderEntity.getDocumentId();
        }

        if (id!=null) {
            //更新
            query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
            query.update("tab_doc_id",tabId);
            query.update("quotation_number",removeSpaces(entity.getRef_num()));
            query.update("ref_line",entity.getRef_line());
            query.update("ref_type",removeSpaces(entity.getRef_type()));
            query.update("material_code",removeSpaces(entity.getItem()));
            query.update("material_description",removeSpaces(entity.getDescription()));
            query.update("discounted_price",entity.getEnd_price());
            query.update("RMB_price",entity.getRMB_price());
            query.update("price",entity.getPrice());
            query.update("unit",removeSpaces( entity.getU_m()));
            query.update("order_quantity",entity.getQty_ordered());
            query.update("purchase_quantity",entity.getQty_po());

            query.update("last_update_date",new Date());
            query.eq("co_num", entity.getCo_num());
            query.eq("sales_order_line_number", entity.getCo_line());
            query.doUpdate(PunchOrderItemEntity.class);
        }else{
            //新增
            PunchOrderItemEntity punchOrderItemEntity = new PunchOrderItemEntity();
            punchOrderItemEntity.setId(snowflakeIdWorker.nextId());
            punchOrderItemEntity.setDocumentId(snowflakeIdWorker.nextId());
            punchOrderItemEntity.setCo_num(removeSpaces(entity.getCo_num()));
            punchOrderItemEntity.setCo_line(entity.getCo_line());
            punchOrderItemEntity.setRef_num(removeSpaces(entity.getRef_num()));
            punchOrderItemEntity.setRef_line(entity.getRef_line());
            punchOrderItemEntity.setRef_type(removeSpaces(entity.getRef_type()));
            punchOrderItemEntity.setItem(removeSpaces(entity.getItem()));
            punchOrderItemEntity.setDescription(removeSpaces(entity.getDescription()));
            punchOrderItemEntity.setEnd_price(entity.getEnd_price());
            punchOrderItemEntity.setRMB_price(entity.getRMB_price());
            punchOrderItemEntity.setPrice(entity.getPrice());
            punchOrderItemEntity.setU_m(removeSpaces( entity.getU_m()));
            punchOrderItemEntity.setQty_ordered(entity.getQty_ordered());
            punchOrderItemEntity.setQty_po(entity.getQty_po());
            punchOrderItemEntity.setQty_shipped(entity.getQty_shipped());
            punchOrderItemEntity.setQty_manufacture(entity.getQty_manufacture());
            punchOrderItemEntity.setDue_date(removeSpaces(entity.getDue_date()));
            punchOrderItemEntity.setShip_date(removeSpaces(entity.getShip_date()));
            punchOrderItemEntity.setCust_po(removeSpaces(entity.getCust_po()));
            punchOrderItemEntity.setCust_item(removeSpaces(entity.getCust_item()));
            punchOrderItemEntity.setQty_rsvd(entity.getQty_rsvd());
            punchOrderItemEntity.setStat(removeSpaces(entity.getStat()));
            punchOrderItemEntity.setProd_class1(removeSpaces(entity.getProd_class1()));
            punchOrderItemEntity.setProd_class2(removeSpaces(entity.getProd_class2()));
            punchOrderItemEntity.setWhse(removeSpaces(entity.getWhse()));
            punchOrderItemEntity.setDeal_mode(removeSpaces(entity.getDeal_mode()));
            punchOrderItemEntity.setMake_add_no(removeSpaces(entity.getMake_add_no()));
            punchOrderItemEntity.setRvid(entity.getRvid());
            punchOrderItemEntity.setTabDocId(tabId);
            query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
            query.doInsert(punchOrderItemEntity);
        }

    }

    public int countOrderItems(Long rv) {
        int count=0;
        Gson gson = new GsonBuilder().create();
        Map<String, String> params=new HashMap<>();
        Map<String, String> headers=new HashMap<>();
        //https://pisi.punch.com.cn:8498/CRM/api/CO/Count/{rv}
        String response = okHttpUtils.doGet(punchConfig.getUrl().concat("/CRM/api/COItem/Count/"+rv.toString()), params,headers);
        PunchResponse punchResponse = gson.fromJson(response, new TypeToken<PunchResponse>(){}.getType());
        count=Integer.parseInt(punchResponse.getResult());
        return count;
    }

    public ResponseVo saveOrderProductByNo(String conum) {

        Gson gson = new GsonBuilder().create();
        Map<String, String> params=new HashMap<>();
        Map<String, String> headers=new HashMap<>();
        headers.put("Authorization", "Bearer "+getPunchToken());
        String response = okHttpUtils.doGet(getPunchUrl().concat("/CRM/api/COItem/"+conum), params,headers);
        PunchResponse punchResponse = gson.fromJson(response, new TypeToken<PunchResponse>(){}.getType());
        List<PunchOrderItemResponseEntity> list = gson.fromJson(punchResponse.getResult(), new TypeToken<List<PunchOrderItemResponseEntity>>(){}.getType());
        for(PunchOrderItemResponseEntity punchOrderItemResponseEntity:list){
            saveOrUpdateOrderItem(punchOrderItemResponseEntity);
        }

        return ResponseVo.ok();
    }

}
